package com.test.netty.websocket;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.EncryptedPrivateKeyInfo;

import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

@Slf4j
public class WebSocketHandler extends SimpleChannelInboundHandler<Object> {

    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(WSConfig.WEBSOCKET_URL, null, false);

    private WebSocketServerHandshaker handshaker;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {// 传统http请求
            httpRequest(ctx, (FullHttpRequest) msg);
        } else if (msg instanceof WebSocketFrame) {// websocket请求
            webSocketRequest(ctx, (WebSocketFrame) msg);
//            for(int i = 0; i < 9999; i++) {
//                final int ii = i;
//                new Thread((Runnable) () -> {
//                    ChannelFuture cf = ctx.channel().writeAndFlush(new TextWebSocketFrame("===>CF:" + ii+ "||ThreadId:" + Thread.currentThread().getId()));
//                    cf.addListener((ChannelFutureListener) future -> {
//                        log.info("===>I:" + ii + "||ThreadId:" + Thread.currentThread().getId());
//                    });
//                }).start();
//            }
        }
    }

    private void httpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
        //Not WebSocket
        if (!req.decoderResult().isSuccess() || (!"websocket".equals(req.headers().get("Upgrade")))) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
            return;
        }
        //WebSocket Handshake
        handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), req);
        }
    }

    private void webSocketRequest(ChannelHandlerContext ctx, WebSocketFrame frame) {
        //
        if (frame instanceof CloseWebSocketFrame) {
            log.debug("Receive CloseWebSocketFrame = " + frame + "  Closing channel  =>> " + ctx.channel().remoteAddress());
            ctx.close();
            return;
        }
        // ping消息
        if (frame instanceof PingWebSocketFrame) {
            log.info("客户端ping成功");
            ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content().retain()));
            return;
        }
        // ping消息
//        if (frame instanceof PongWebSocketFrame) {
//            log.info("客户端pong成功");
//            return;
//        }
        // 二进制消息
        if (frame instanceof BinaryWebSocketFrame) {
            return;
        }

        if (!(frame instanceof TextWebSocketFrame)) {
            throw new UnsupportedOperationException(
                    String.format("%s frame types not supported", frame.getClass().getName()));
        }
        String text = ((TextWebSocketFrame) frame).text();
        log.info("Receive TextWebSocketFrame => " + text + " From Client ==> " + ctx.channel().remoteAddress());
        ctx.channel().writeAndFlush(new TextWebSocketFrame(System.currentTimeMillis() + text));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("channelActive" + ctx.name());
    }

    private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
        if (res.status().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
            HttpUtil.setContentLength(res, res.content().readableBytes());
        }
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }

}
